<template>
  <div class="wine-cart">
    <!-- 购物车标题 -->
    <div class="cart-header">
      <h2>
        <el-icon><ShoppingCart /></el-icon>
        购物车 ({{ cartItems.length }})
      </h2>
      <el-button v-if="cartItems.length > 0" type="danger" text @click="clearCart"> 清空购物车 </el-button>
    </div>

    <!-- 购物车内容 -->
    <div class="cart-content">
      <!-- 空购物车状态 -->
      <el-empty v-if="cartItems.length === 0" description="购物车是空的，去选购您喜欢的酒品吧！" :image-size="120">
        <el-button type="primary" @click="$emit('goShopping')"> 去购物 </el-button>
      </el-empty>

      <!-- 购物车商品列表 -->
      <div v-else class="cart-items">
        <el-card v-for="item in cartItems" :key="item.id" class="cart-item" shadow="hover">
          <div class="item-content">
            <!-- 商品图片 -->
            <div class="item-image">
              <el-image :src="item.image" :alt="item.name" fit="cover" style="width: 80px; height: 80px">
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>

            <!-- 商品信息 -->
            <div class="item-info">
              <h4 class="item-name">{{ item.name }}</h4>
              <p class="item-description">{{ item.description }}</p>
              <div class="item-specs">
                <el-tag size="small">{{ item.category }}</el-tag>
                <el-tag size="small" type="info">{{ item.alcohol }}°</el-tag>
                <el-tag size="small" type="warning">{{ item.volume }}ml</el-tag>
              </div>
            </div>

            <!-- 价格和数量控制 -->
            <div class="item-controls">
              <div class="item-price">
                <span class="current-price">¥{{ item.price }}</span>
                <span v-if="item.originalPrice > item.price" class="original-price"> ¥{{ item.originalPrice }} </span>
              </div>

              <!-- 数量控制器 -->
              <div class="quantity-control">
                <el-input-number v-model="item.quantity" :min="1" :max="item.stock" size="small" @change="updateQuantity(item)" />
              </div>

              <!-- 小计 -->
              <div class="item-subtotal">小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</div>

              <!-- 删除按钮 -->
              <el-button type="danger" text size="small" @click="removeItem(item.id)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 购物车底部统计 -->
    <div v-if="cartItems.length > 0" class="cart-footer">
      <el-card class="cart-summary">
        <div class="summary-content">
          <div class="summary-info">
            <div class="summary-line">
              <span>商品总数：</span>
              <span>{{ totalQuantity }} 件</span>
            </div>
            <div class="summary-line">
              <span>商品总额：</span>
              <span class="original-total">¥{{ totalOriginalAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-line discount" v-if="totalDiscount > 0">
              <span>优惠金额：</span>
              <span>-¥{{ totalDiscount.toFixed(2) }}</span>
            </div>
            <div class="summary-line total">
              <span>应付总额：</span>
              <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="checkout-actions">
            <el-button size="large" @click="continueShopping"> 继续购物 </el-button>
            <el-button type="primary" size="large" @click="proceedToCheckout" :disabled="!canCheckout"> 去结算 </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 缺货提醒对话框 -->
    <el-dialog v-model="showStockDialog" title="库存不足提醒" width="400px">
      <p>{{ stockDialogMessage }}</p>
      <template #footer>
        <el-button @click="showStockDialog = false">知道了</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElCard, ElButton, ElEmpty, ElImage, ElTag, ElInputNumber, ElIcon, ElDialog, ElMessage } from 'element-plus'
import { ShoppingCart, Delete, Picture } from '@element-plus/icons-vue'

export default {
  name: 'WineShoppingCart',
  components: {
    ElCard,
    ElButton,
    ElEmpty,
    ElImage,
    ElTag,
    ElInputNumber,
    ElIcon,
    ElDialog,
    ShoppingCart,
    Delete,
    Picture
  },
  emits: ['goShopping', 'checkout', 'continueShopping'],
  setup(props, { emit }) {
    // 示例购物车数据
    const cartItems = ref([
      {
        id: 1,
        name: '茅台酒 飞天53度',
        description: '贵州茅台酒股份有限公司出品，酱香型白酒经典',
        category: '白酒',
        alcohol: 53,
        volume: 500,
        price: 2899,
        originalPrice: 3299,
        quantity: 1,
        stock: 10,
        image: 'https://images.unsplash.com/photo-1569529465841-dfecdab7503b?w=300&h=300&fit=crop'
      },
      {
        id: 2,
        name: '五粮液 52度',
        description: '宜宾五粮液股份有限公司出品，浓香型白酒',
        category: '白酒',
        alcohol: 52,
        volume: 500,
        price: 1299,
        originalPrice: 1299,
        quantity: 2,
        stock: 5,
        image: 'https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=300&h=300&fit=crop'
      },
      {
        id: 3,
        name: '轩尼诗XO',
        description: '法国进口干邑白兰地，醇香浓郁',
        category: '洋酒',
        alcohol: 40,
        volume: 700,
        price: 1899,
        originalPrice: 2199,
        quantity: 1,
        stock: 3,
        image: 'https://images.unsplash.com/photo-1618411640119-ad57cc2f4115?w=300&h=300&fit=crop'
      }
    ])

    const showStockDialog = ref(false)
    const stockDialogMessage = ref('')

    // 计算属性
    const totalQuantity = computed(() => {
      return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
    })

    const totalOriginalAmount = computed(() => {
      return cartItems.value.reduce((sum, item) => sum + item.originalPrice * item.quantity, 0)
    })

    const totalAmount = computed(() => {
      return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
    })

    const totalDiscount = computed(() => {
      return totalOriginalAmount.value - totalAmount.value
    })

    const canCheckout = computed(() => {
      return cartItems.value.length > 0 && cartItems.value.every(item => item.quantity <= item.stock)
    })

    // 方法
    const updateQuantity = item => {
      if (item.quantity > item.stock) {
        stockDialogMessage.value = `${item.name} 库存不足，当前库存：${item.stock} 件`
        showStockDialog.value = true
        item.quantity = item.stock
      }

      ElMessage.success('数量已更新')
    }

    const removeItem = itemId => {
      const index = cartItems.value.findIndex(item => item.id === itemId)
      if (index > -1) {
        const itemName = cartItems.value[index].name
        cartItems.value.splice(index, 1)
        ElMessage.success(`${itemName} 已从购物车中移除`)
      }
    }

    const clearCart = () => {
      cartItems.value = []
      ElMessage.success('购物车已清空')
    }

    const continueShopping = () => {
      emit('continueShopping')
    }

    const proceedToCheckout = () => {
      if (!canCheckout.value) {
        ElMessage.warning('请检查商品库存后再结算')
        return
      }

      const checkoutData = {
        items: cartItems.value,
        totalAmount: totalAmount.value,
        totalQuantity: totalQuantity.value,
        totalDiscount: totalDiscount.value
      }

      emit('checkout', checkoutData)
    }

    return {
      cartItems,
      showStockDialog,
      stockDialogMessage,
      totalQuantity,
      totalOriginalAmount,
      totalAmount,
      totalDiscount,
      canCheckout,
      updateQuantity,
      removeItem,
      clearCart,
      continueShopping,
      proceedToCheckout
    }
  }
}
</script>

<style scoped>
.wine-cart {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.cart-header h2 {
  margin: 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cart-content {
  margin-bottom: 20px;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cart-item {
  transition: transform 0.2s;
}

.cart-item:hover {
  transform: translateY(-2px);
}

.item-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-image {
  flex-shrink: 0;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background: #f5f7fa;
  color: #909399;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.item-description {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.item-specs {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.item-controls {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  min-width: 120px;
}

.item-price {
  text-align: right;
}

.current-price {
  color: #e6a23c;
  font-size: 18px;
  font-weight: 600;
}

.original-price {
  color: #909399;
  font-size: 14px;
  text-decoration: line-through;
  margin-left: 8px;
}

.quantity-control {
  width: 120px;
}

.item-subtotal {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.cart-footer {
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 100;
}

.cart-summary {
  border: 2px solid #409eff;
}

.summary-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.summary-info {
  flex: 1;
}

.summary-line {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-line.discount {
  color: #67c23a;
}

.summary-line.total {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  border-top: 1px solid #ebeef5;
  padding-top: 8px;
  margin-top: 8px;
}

.original-total {
  color: #909399;
  text-decoration: line-through;
}

.total-amount {
  color: #f56c6c;
  font-size: 24px;
}

.checkout-actions {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wine-cart {
    padding: 10px;
  }

  .cart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .item-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .item-controls {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .summary-content {
    flex-direction: column;
    align-items: stretch;
  }

  .checkout-actions {
    width: 100%;
  }

  .checkout-actions .el-button {
    flex: 1;
  }
}
</style>
